package com.cenntro.common.aliyun;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import com.aliyun.oss.OSSClient;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FileUpload {

    public static String ENDPOINT = "http://oss-cn-hangzhou.aliyuncs.com";

    public static String ACCESSKEYID = "LTAI4okMSTvTx5UY";

    public static String ACCESSKEYSECRET = "E9jZzR7i9MiA1tEuSJpzHcwLMD3atb";

    public static String BUCKETNAME = "cenntro";

    public static String KEY = "1/zhcl_pic/";

    public static String BUCKET_URL = "http://cenntro.oss-cn-hangzhou.aliyuncs.com";

    /**
     * 阿里云文件上传文件夹 oss
     */
    public static String PREFIX_OSS = "oss";

    /**
     * 阿里云文件上传文件夹 repair
     */
    public static String PREFIX_REPAIR = "repair";

    /**
     * 上传文件 
     * @param request
     * @return
     */
    public String upload(HttpServletRequest request) {
        String fileNames = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmsss");
        String strUrl = "";
        OSSClient ossClient = null;
        try {
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            Iterator<String> iterator = req.getFileNames();
            while (iterator.hasNext()) {
                String url = sdf.format(new Date());
                MultipartFile file = req.getFile(iterator.next());
                fileNames = file.getOriginalFilename();
                InputStream input = file.getInputStream();
                url = KEY + url + "_" + fileNames;
                // 创建OSSClient实例
                ossClient = new OSSClient(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);
                // 上传文件流
                ossClient.putObject(BUCKETNAME, url, input);
                strUrl += BUCKET_URL + "/" + url + "|";
            }
        } catch (IOException e) {
            log.info("上传文件到 对象存储Oss 失败，", e);
            e.printStackTrace();
        }finally {
            if(ossClient != null){
                ossClient.shutdown();
            }
        }
        if (strUrl.endsWith("|")) {
            strUrl = strUrl.substring(0, strUrl.length() - 1);
        }
        return strUrl;
    }

    /**
     * 
    * @Title upload
    * @Description 上次文件到阿里云 对象存储Oss
    * @param Prefix  项目前缀
    * @return
     */
    public String upload(HttpServletRequest request, String prefix) {
        String strUrl = "";
        if (StringUtils.isBlank(prefix)) {
            prefix = "default";
        }
        String fileNames = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmsss");
        OSSClient ossClient = null;
        try {
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            Iterator<String> iterator = req.getFileNames();
            String dateStr = sdf.format(new Date());
            String url = null;
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                fileNames = file.getOriginalFilename();
                InputStream input = file.getInputStream();
                url = prefix + "/" + dateStr + "/" + dateStr + "_" + fileNames;
                // 创建OSSClient实例
                ossClient = new OSSClient(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);
                // 上传文件流
                ossClient.putObject(BUCKETNAME, url, input);
                strUrl += BUCKET_URL + "/" + url + "|";
            }
        } catch (IOException e) {
            log.info("上传文件到 对象存储Oss 失败，", e);
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        if (strUrl.endsWith("|")) {
            strUrl = strUrl.substring(0, strUrl.length() - 1);
        }
        return strUrl;
    }

    /**
     * 删除文件
     * @param filename
     * @return
     */
    public void deleteFile(String filename) {
        if (StringUtils.isBlank(filename)) {
            return;
        }
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = ENDPOINT;
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录
        // https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = ACCESSKEYID;
        String accessKeySecret = ACCESSKEYSECRET;
        String bucketName = BUCKETNAME;
        String objectName = filename.replace(ENDPOINT, "");
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 删除文件。
        ossClient.deleteObject(bucketName, objectName);
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    public static void main(String[] args) {
        // http://cenntro.oss-cn-hangzhou.aliyuncs.com/1/zhcl_pic/201903281427039_picName.jpg
        new FileUpload().deleteFile("1/zhcl_pic/20190326172715_Koala.jpg");
    }
}
